<?php

class UsersController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('recovery', 'activation', 'forgetpassword', 'sendMailtouserpromotion', 'trainerProfile', 'trainer', 'setUserSession', 'subscribe', 'runningclasses', 'previousclasses', 'userRegistration'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('learnUser', 'checkProfile', 'changepassword', 'trainerordersummery', 'editprofile', 'userRegistration', 'myskillhippo', 'myprofile', 'updateprofile', 'Uploadphoto'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionforgetpassword() {
        if (isset($_POST['Users'])) {
            $users = Users::model()->findByAttributes(array('username' => $_POST['Users']['username']));
            if (!empty($users)) {
                $users->setAttribute('activationKey', guid());
                $users->save();
                $activation_key = $users->activationKey;
                $this->forgatePasswordEmail($users->username, $activation_key);
                echo CJSON::encode(array(
                    'status' => 'success',
                ));
                Yii::app()->end();
            } else {
                echo CJSON::encode(array(
                    'error' => 'Username/Email-address is incorrect.',
                ));
                Yii::app()->end();
            }
        }
    }

    public function actionRecovery() {
        if (isset($_GET['username']) && isset($_GET['activationKey'])) {
            $model = new Users;
            $email = $_GET['username'];
            $activationKey = $_GET['activationKey'];
            $users = Users::model()->findByAttributes(array('username' => $email, 'activationKey' => $activationKey));
            if (!empty($users) && $users->activationKey == $activationKey) {
                if (isset($_POST['Users'])) {
                    $model->attributes = $_POST['Users'];
                    if ($model->validate()) {
                        $users->password = md5($_POST['Users']['password']);
                        $users->activationKey = guid() . time();
                        $users->save();
                        $identity = new UserIdentity($users->username, $_POST['Users']['password']);
                        $identity->authenticate();
                        Yii::app()->user->login($identity);
                        $_SESSION['id'] = Yii::app()->user->id;
                        $this->redirect(Yii::app()->controller->createUrl("/myskillhippo"));
                    }
                }
                $this->render('/users/recovery-change-password', array('model' => $model));
            }
            throw new CHttpException(403, "Skillhippo!, you are not authorized to perform this action.");
        }
    }

    private function forgatePasswordEmail($username, $activation_key) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::FORGOTPASSWORD_TEMPLATE);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $activation_url = '<a class="linkclass"  href="http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('users/recovery', array("activationKey" => $activation_key, "username" => $username)) . '" target="_blank">Change-password Link</a>';
        $subject = $mailmodel->subject;
        $mailto = $username;
        $arrayFind = array('[username]', '[activation_key]', '[activation_link]');
        $arrayReplace = array($mailto, $activation_key, $activation_url);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);       
        $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            /* $this->redirect(array('view', 'id' => $model->id)); */
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function actionActivation() {
        $user = new Users();
        $returnUrl = Yii::app()->controller->createUrl("/myskillhippo");
        if ($user->activate($_GET['skillusers'],$_GET['activationKey'])) {
            $udata = $user->findByAttributes(array('username' => $_GET['skillusers']));       
            if (isset($udata) && !empty($udata)) {            
                $this->senduserActivationEmail($_GET['skillusers']);
                $loginpassword = $udata->password;               
                $udata->password = md5($loginpassword);
                $udata->save();
                $identity = new UserIdentity($_GET['skillusers'], $loginpassword);
                $identity->authenticate();              
                Yii::app()->user->login($identity);
                $_SESSION['id'] = Yii::app()->user->id;
                if (!empty(Yii::app()->session['class_course_review'])) {
                    $returnUrl = Reviews::saveReviewAfterloginuser();
                }
                if (!empty(Yii::app()->session['trainer_profile_review'])) {
                    $returnUrl = TrainerProfileReview::savetrainerReviewAfterloginuser();
                }
                if (!empty(Yii::app()->session['make_query'])) {
                    $returnUrl = MakeQuery::makequeryafterloginuser();
                }
                if (!empty(Yii::app()->session['trainer_follower'])) {
                    $returnUrl = TrainerFollow::saveTrainerfollowersafterlogin();
                }
                if (!empty(Yii::app()->session['shopping_cart_session'])) {
                    $returnUrl = Yii::app()->createAbsoluteUrl('ShoppingCart/skillshopping');
                }
                $this->redirect($returnUrl);
            }
        } else {
            $this->render('/users/usersactivation', array(
                'content' => Yii::t("Users", "Incorrect activation link.")));
        }
    }

    public function senduserActivationEmail($usermail) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::WELCOME_MSG_REGISTRATION);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $usermail;
        $arrayFind = array('[username]');
        $arrayReplace = array($mailto);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('//mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function actionuserRegistration() {       
        $registraion = '';
        $returnUrl = '';
        $user = Users::model()->findByAttributes(array('username' => $_POST['Users']['username'], 'status' => 0));
        $model = (!empty($user)) ? $user : new Users;
        $loginpassword = $_POST['Users']['password'];
        if (isset($_POST['Users']['password'])) {
            $model->attributes = $_POST['Users'];
            $model->activationKey = guid() . time();
            $model->createtime = time();
            if (isset($_POST['Users']['issubscribe'])) {
                $model->issubscribe = $_POST['Users']['issubscribe'];
            }
            $model->superuser = SkillConfig::STATUS_DEACTIVE;
            $model->is_users = SkillConfig::STATUS_ACTIVE;
            $model->status = SkillConfig::STATUS_DEACTIVE;
            $valid = $model->validate();
            if ($valid) {
                $model->save(FALSE);
                $userRole = new UserHasRole();
                $userRole->setAttribute('role_id', SkillConfig::WEB_USER);
                $userRole->setAttribute('user_id', $model->id);
                $userRole->save(false);
                $profile = new Profiles();
                $profile->termcondition = SkillConfig::STATUS_ACTIVE;
                $profile->user_id = $model->id;
                $profile->save();
               $this->sendRegistrationmail($model);
                if (!empty(Yii::app()->session['shopping_cart_session'])) {
                    //this line when value add in shopping cart
                    $model->password=
                    $registraion = 1;
                    $identity = new UserIdentity($model->username, $loginpassword);
                    $identity->authenticateshoppng();                  
                    Yii::app()->user->login($identity);
                    $_SESSION['id'] = Yii::app()->user->id;
                    $returnUrl = Yii::app()->createAbsoluteUrl('ShoppingCart/skillshopping');
                }
                echo CJSON::encode(array(
                    'status' => 'success',
                    'authenticated' => $registraion,
                    'redirectUrl' => $returnUrl,
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    private function sendRegistrationmail($user) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::REGISTRATION_TEMPLATE);
        $activation_url = '<a class="linkclass" href="http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('Users/activation', array("activationKey" => $user->activationKey, "skillusers" => $user->username)) . '" target="_blank">Activation Link</a>';
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $user->username;
        $arrayFind = array('[username]', ' [activation_key]', '[activation_link]');
        $arrayReplace = array($mailto, $user->activationKey, $activation_url);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            /* $this->redirect(array('view', 'id' => $model->id)); */
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function actionTrainerProfile($authKey) {
        $classTrainerRate = '';
        $classCoursename = '';
        $classtotalCountTrainerate = '';
        $action = '';
        $loginUserId = getLoginUserId();
        $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
        $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
        if (!empty($classes) || !empty($courses)) {
            if (!empty($classes)) {
                $profiles = getUserTypeByClassCourse('Classes', $classes->id);
                $userType = getUserType('Classes', $classes->id);
                $classesCourse = $classes;
                $classtype = 'class';
                $imagePath = getImagePathByClassCourse('Classes', $classes->id);
                $classTrainerRate = Classes::trainerPossitiverate($userType, $classes);
                $classtotalCountTrainerate = Classes::trainertotalRate($userType, $classes);
                $classCoursename = $classes->class_titile;
                $action = 'workshop-'.$classes->id.'/'.$classes->class_seo_title;
            }
            if (!empty($courses)) {
                $classtype = 'course';
                $classesCourse = $courses;
                $profiles = getUserTypeByClassCourse('Courses', $courses->id);
                $userType = getUserType('Courses', $courses->id);
                $imagePath = getImagePathByClassCourse('Courses', $courses->id);
                $classTrainerRate = Classes::trainerPossitiverate($userType, $courses);
                $classtotalCountTrainerate = Classes::trainertotalRate($userType, $courses);
                $classCoursename = $courses->course_titile;
                $action = 'courses-'.$courses->id.'/'.$courses->course_seo_title;
            }
            $trainerType = ($userType != 'backend') ? 'trainer_front_end_user_id' : 'trainer_backend_user_id';
            $trainerFolow = count(TrainerFollow::model()->findByAttributes(array('folower_user_id' => $loginUserId, $trainerType => $profiles->user_id)));
            $folowers = ($trainerFolow > 0) ? Message::FOLOWER_ON_SKILLHIPPO : Message::FOLOW_ON_SKILLHIPPO;
            $this->render('trainerProfile', array('classtype' => $classtype, 'profiles' => $profiles, 'classes' => $classesCourse, 'imagePath' => $imagePath, 'userType' => $userType,
                'action' => $action, 'classCoursename' => $classCoursename, 'classTrainerRate' => $classTrainerRate, 'classtotalCountTrainerate' => $classtotalCountTrainerate,
                'authKey' => $authKey, 'folowers' => $folowers));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionlearnUser() {
        $this->layout = FALSE;
        $purchaseClassCourse = new CActiveDataProvider('PurchaseOrder', array(
            'criteria' => array(
                'condition' => 'users_id=' . getLoginUserId(),
                'order' => 'id DESC',
            ),
        ));
        $dataProvider = new CActiveDataProvider('MakeQuery', array(
            'criteria' => array(
                'condition' => 'users_id=' . getLoginUserId(),
                'order' => 'id DESC',
            ),
        ));

        $this->render('learn', array('dataProvider' => $dataProvider, 'purchaseClassCourse' => $purchaseClassCourse));
    }

    public function actionsubscribe() {
        $this->layout = false;
        $model = new Users;
        if (!empty($_POST['Users'])) {
            $model->setScenario('updateSubscription'); // 
            $model->setAttributes($_POST['Users']);
            $model->setAttribute('password', 'subscribe');
            $model->setAttribute('confirm_password', 'subscribe');
            if ($model->validate()) {
                $userDetail = $model->findByAttributes(array('username' => $model->username));
                if (isset($userDetail->id)) {
                    /* User already exist */
                    if ($userDetail->id <> "" && $userDetail->issubscribe == SkillConfig::STATUS_ACTIVE) {
                        echo CJSON::encode(array(
                            'status' => 'already_subscribe'
                        ));
                        Yii::app()->end();
                    } else {
                        $model->updateByPk($userDetail->id, array('issubscribe' => SkillConfig::STATUS_ACTIVE));
                        echo CJSON::encode(array(
                            'status' => 'success'
                        ));
                        Yii::app()->end();
                    }
                } else {
                    $model->setAttribute('status', SkillConfig::STATUS_DEACTIVE);
                    $model->setAttribute('issubscribe', SkillConfig::STATUS_ACTIVE);
                    $model->save();
                    $mailmodel = EmailTemplate::model()->findByPk(Message::NEWS_LETTER);
                    $userText = $mailmodel->body;
                    $mailbody = array('value' => $userText, 'type' => 'raw');
                    $subject = $mailmodel->subject;
                    $userName = $model->username;
                    $mailto = $model->username;
                    $arrayFind = array('[username]');
                    $arrayReplace = array($userName);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                        Promotion::promotioncoupon(Message::DISCOUNT_COUPON_NEWSLETTER, $mailto);
                        echo CJSON::encode(array(
                            'status' => 'success'
                        ));

                        Yii::app()->end();
                    } catch (Exception $e) {
                        $result = $e;
                        exit;
                    }
                }
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    public function actionrunningclasses($authKey) {
        $cs = Yii::app()->clientScript;
        $cs->scriptMap = array('jquery-1.11.0.min.js' => false,);
        $allClassCourseInfo = array();
        $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
        $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
        if (!empty($classes) || !empty($courses)) {
            if (!empty($classes)) {
                $profiles = getUserTypeByClassCourse('Classes', $classes->id);
                $userType = getUserType('Classes', $classes->id);
            }
            if (!empty($courses)) {
                $profiles = getUserTypeByClassCourse('Courses', $courses->id);
                $userType = getUserType('Courses', $courses->id);
            }
            if (isset($_GET['type']) && $_GET['type'] == 'course') {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $allClassCourseInfo = runningCurrentCoursesByUser($profiles, $userType, $_GET);
                } else {
                    $allClassCourseInfo = runningCurrentCoursesByUser($profiles, $userType, $_GET);
                    usort($allClassCourseInfo, 'date_compare');
                }
            } elseif (isset($_GET['type']) && ($_GET['type'] == 'workshop' OR $_GET['type'] == 'curatedclasses')) {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $allClassCourseInfo = literalEndingTommorow($profiles, $userType, $_GET);
                    $comapreFunction = ($_GET['priceorder'] == '1' ? 'price_compare_ascending' : ($_GET['priceorder'] == '2' ? 'price_compare_descending' : ($_GET['mostpopular'] == '1' ? 'hitcounter_compare_descending' : 'hitcounter_compare_ascending')));
                    usort($allClassCourseInfo, $comapreFunction);
                } else {
                    $allClassCourseInfo = literalEndingTommorow($profiles, $userType, $_GET);
                }
            } else {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $classDetails = literalEndingTommorow($profiles, $userType, $_GET);
                    $courseDetails = runningCurrentCoursesByUser($profiles, $userType, $_GET); //Null parameter means these value $profiles, $userType, $getValue)
                    $allClassCourseInfo = array_merge($classDetails, $courseDetails);
                    $comapreFunction = ($_GET['priceorder'] == '1' ? 'price_compare_ascending' : ($_GET['priceorder'] == '2' ? 'price_compare_descending' : ($_GET['mostpopular'] == '1' ? 'hitcounter_compare_descending' : 'hitcounter_compare_ascending')));
                    usort($allClassCourseInfo, $comapreFunction);
                } else {
                    $classDetails = literalEndingTommorow($profiles, $userType, $_GET);
                    $courseDetails = runningCurrentCoursesByUser($profiles, $userType, $_GET); //Null parameter means these value $profiles, $userType, $getValue)
                    $allClassCourseInfo = array_merge($classDetails, $courseDetails);
                    usort($allClassCourseInfo, 'date_compare');
                }
            }
            $dataProvider = new CArrayDataProvider($allClassCourseInfo, array(
                'sort' => array(
                    'attributes' => array(
                        'start_date',
                    ),
                ),
                'pagination' => array(
                    'pageSize' => 20,
                ),
            ));

            $this->render('_runningClasses', array('dataProvider' => $dataProvider, 'profiles' => $profiles, 'userType' => $userType,
                'authKey' => $authKey));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionpreviousclasses($authKey) {
        $cs = Yii::app()->clientScript;
        $cs->scriptMap = array('jquery-1.11.0.min.js' => false,);
        $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
        $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
        $classTypecourse = 'priviousClasses';
        if (!empty($classes) || !empty($courses)) {
            if (!empty($classes)) {
                $profiles = getUserTypeByClassCourse('Classes', $classes->id);
                $userType = getUserType('Classes', $classes->id);
            }
            if (!empty($courses)) {
                $profiles = getUserTypeByClassCourse('Courses', $courses->id);
                $userType = getUserType('Courses', $courses->id);
            }
            if (isset($_GET['type']) && $_GET['type'] == 'course') {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $coursesArray = previousCourseByuser($profiles, $userType);
                }
            } elseif (isset($_GET['type']) && ($_GET['type'] == 'workshop' OR $_GET['type'] == 'curatedclasses')) {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $coursesArray = previousClassByuser($profiles, $userType);
                    $comapreFunction = ($_GET['priceorder'] == '1' ? 'price_compare_ascending' : ($_GET['priceorder'] == '2' ? 'price_compare_descending' : ($_GET['mostpopular'] == '1' ? 'hitcounter_compare_descending' : 'hitcounter_compare_ascending')));
                    usort($coursesArray, $comapreFunction);
                }
            } else {
                $courseDetails = previousCourseByuser($profiles, $userType);
                $classDetails = previousClassByuser($profiles, $userType);
                $coursesArray = array_merge($classDetails, $courseDetails);
                usort($coursesArray, 'date_compare');
            }

            $dataProvider = new CArrayDataProvider($coursesArray, array(
                'sort' => array(
                    'attributes' => array(
                        'start_date',
                    ),
                ),
                'pagination' => array(
                    'pageSize' => 6,
                ),
            ));

            $this->render('_previusClasses', array('dataProvider' => $dataProvider, 'profiles' => $profiles,
                'authKey' => $authKey, 'classTypecourse' => $classTypecourse));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionsetUserSession() {
        if ($_POST['sessionVal'] != '2') {
            Yii::app()->user->setState('trainer', SkillConfig::USER_TRAINER);
        }
        if ($_POST['sessionVal'] != '1') {
            Yii::app()->user->setState('trainer', SkillConfig::WEB_USER);
        }
    }

    public function actiontrainerordersummery() {
        $this->layout = FALSE;
        $this->render('trainerordersummery');
    }

    public function actionsendMailtouserpromotion($couponName, $username) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::COUPON_SEND_TO_USER);
        $userText = $mailmodel->body;
        $mailbody = array('value' => $userText, 'type' => 'raw');
        $mailto = $username;
        $arrayFind = array('[username]', '[coupon_code]');
        $arrayReplace = array($username, $couponName);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('//mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
        } catch (Exception $e) {
            $result = $e;
            exit;
        }
    }

    public function actionmyprofile() {
        $classTrainerRate = '';
        $classtotalCountTrainerate = '';
        $this->layout = false;
        $profiles = Users::getFrontEndUser(getLoginUserId());
        $class = Classes::model()->findByAttributes(array('users_id' => getLoginUserId()));
        $courses = Courses::model()->findByAttributes(array('users_id' => getLoginUserId()));
        if (!empty($courses)) {
            $classTrainerRate = Classes::trainerPossitiverate('front-end', $courses);
            $classtotalCountTrainerate = Classes::trainertotalRate('front-end', $courses);
        }
        if (!empty($class)) {
            $classTrainerRate = Classes::trainerPossitiverate('front-end', $class);
            $classtotalCountTrainerate = Classes::trainertotalRate('front-end', $class);
        }
        $this->render('myprofile', array('profiles' => $profiles, 'classTrainerRate' => $classTrainerRate, 'classtotalCountTrainerate' => $classtotalCountTrainerate,
        ));
    }

    public function actionmyskillhippo() {
        $proiles = Users::getFrontEndUser(getLoginUserId());
        $profileUrl = (!empty($proiles->first_name)) ? $this->createUrl('/users/myprofile/') : $this->createUrl('/users/editprofile/');
        $this->render('myskillhippo', array('profileUrl' => $profileUrl));
    }

    public function actionupdateprofile() {
        $this->layout = FALSE;
        $isCorporate = '';
        $profiles = Profiles::model()->findByAttributes(array('user_id' => getLoginUserId()));
        $cmsContent = getCMSConetnt(Message::TERMS_US_ID);
        $corporateprogram = (!$profiles->corporateprogram) ? new CorporateProgram() : $profiles->corporateprogram;

        if (isset($_POST['Profiles'])) {
            $profiles->attributes = $_POST['Profiles'];
            $valid = $profiles->validate();
//$valid = $profiles->validate();
//code for corporate program start//
//            if (isset($_POST['isCorporate']) && $_POST['isCorporate'] == 1) {
//                $corporateprogram->attributes = $_POST['CorporateProgram'];
//                $corporateprogram->profiles_id = $profiles->profile_id;
//                $corporateprogram->users_id = Yii::app()->user->id;
//                $valid = $corporateprogram->validate() && $valid;
//                $isCorporate = $_POST['isCorporate'];
//            } else {
//                if (!$corporateprogram->isNewRecord) {
//                    $corporateprogram->delete();
//                }
//            }
//code for corporate program end//
            if ($valid) {
                $transaction = Yii::app()->getDb()->beginTransaction();
                try {
                    $profiles->cache_last_updated = date("Y-m-d H:i:s");
                    $subscribeValue = (isset($_POST['RegistrationForm']['issubscribe'])) ? $_POST['RegistrationForm']['issubscribe'] : '0';
                    Users::model()->updateByPk(getLoginUserId(), array('issubscribe' => $subscribeValue));
                    if ($profiles->save()) {
// $corporateprogram->save();
                        makeUploadDir(getLoginUserId());
                    }
                    $transaction->commit();
                    echo CJSON::encode(array(
                        'status' => 'success',
                    ));

                    Yii::app()->end();
// $this->redirect($redirectUrl);
                } catch (Exception $e) {
                    $transaction->rollback();
                    throw $e;
                }
            } else {
                $error = CActiveForm::validate($profiles);

                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    public function actioneditprofile() {
        $this->layout = FALSE;
        $isCorporate = '';
        $profiles = Profiles::model()->findByAttributes(array('user_id' => getLoginUserId()));
        $cmsContent = getCMSConetnt(Message::TERMS_US_ID);
        $corporateprogram = (!$profiles->corporateprogram) ? new CorporateProgram() : $profiles->corporateprogram;
        $folder = getUploadDir() . Yii::app()->user->id . '/'; // folder for uploaded files
        $user = Users::model()->findByAttributes(array('id' => Yii::app()->user->id));
        $deletePicureUrl = Yii::app()->createUrl('user/profile/deletephoto');

        $this->renderPartial('edit_profile', array(
            'profiles' => $profiles,
            'corporateprogram' => $corporateprogram,
            'isCorporate' => $isCorporate,
            'deletePicureUrl' => $deletePicureUrl,
            'userFolder' => $folder,
            'termcondition_value' => $cmsContent->body,
                ), false, true);

//echo $this->renderPartial('edit_profile', array('profiles' => $profiles), false, TRUE);
//echo $this->renderPartial('edit_profile',array('profiles'=>$profiles),true);
    }

    public function actionUploadphoto() {
        $folder = getUploadDir(); // folder for uploaded files
        if (isset($_GET['qqfile']) && isset($_GET['id']) && !empty($_GET['qqfile']) && !empty($_GET['id'])) {
            $user = Users::model()->findByAttributes(array('id' => Yii::app()->user->id));
            makeUploadDir(getLoginUserId());
        }
        $folder = $folder . getLoginUserId() . '/';
        Yii::import("common.extensions.EAjaxUpload.qqFileUploader");
        $allowedExtensions = array("jpg", "jpeg", "gif", "png", "JPG", "JPEG", "GIF", "PNG"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = SkillConfig::MAX_IMAGE_SIZE_UPLOAD; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        if ($result['success']) {
            $profile = Profiles::model()->findByPk((int) $_GET['id']);
            if ($profile->photo <> "" && file_exists($folder . 'profile/' . $profile->photo) && file_exists($folder . 'profile/thumb/' . $profile->photo) && file_exists($folder . 'profile/minithumb/' . $profile->photo) && file_exists($folder . 'profile/432X324/' . $profile->photo)) {
                unlink($folder . 'profile/' . $profile->photo);
                unlink($folder . 'profile/thumb/' . $profile->photo);
                unlink($folder . 'profile/minithumb/' . $profile->photo);
                unlink($folder . 'profile/432X324/' . $profile->photo);
            }
            Profiles::model()->updateByPk($_GET['id'], array(
                'cache_last_updated' => date("Y-m-d H:i:s"),
                'photo' => $result['filename']
            ));
        }

        $return = CJSON::encode($result);
        $fileSize = filesize($folder . 'profile/' . $result['filename']); //GETTING FILE SIZE
        $fileName = $result['filename']; //GETTING FILE NAME
        echo $return;
    }

    public function actionchangepassword() {
        $this->layout = false;
        if (Yii::app()->user->id) {
            if (isset($_POST['password'])) {
                $new_password = Users::model()->findbyPk(getLoginUserId());
                $new_password->password = md5($_POST['password']);
                if ($new_password->save()) {
                    $mailmodel = EmailTemplate::model()->findByPk(Message::RESET_PASSWORD);
                    $userText = $mailmodel->body;
                    $mailbody = array('value' => $userText, 'type' => 'raw');
                    $subject = $mailmodel->subject;
                    $userName = $new_password->username;
                    $mailto = $new_password->username;
                    $arrayFind = array('[username]');
                    $arrayReplace = array($userName);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                        echo "success";
                        Yii::app()->end();
                    } catch (Exception $e) {
                        exit;
                    }
                }
                exit();
            }
        }
    }

    public function actioncheckProfile() {
        $profile = Profiles::model()->findByAttributes(array('user_id' => getLoginUserId()));
        if (isset($_POST['action'])) {
            if ($profile->first_name == '') {
                echo SkillConfig::STATUS_ACTIVE;
            } else {
                echo Yii::app()->createAbsoluteUrl($_POST['action']);
            }
        }
    }

    public function actiontrainer() {
        $model = new Users;
        if (isset($_POST['Users']['password'])) {
            $model->attributes = $_POST['Users'];
            $model->activationKey = guid() . time();
            $model->createtime = time();
            if (isset($_POST['Users']['issubscribe'])) {
                $model->issubscribe = $_POST['Users']['issubscribe'];
            }
            $model->superuser = SkillConfig::STATUS_DEACTIVE;
            $model->is_users = SkillConfig::STATUS_ACTIVE;
            $model->status = SkillConfig::STATUS_DEACTIVE;
            $valid = $model->validate();
            if ($valid) {
                $model->setAttribute('password', md5($_POST['Users']['password']));
                $model->save(FALSE);
                $userRole = new UserHasRole();
                $userRole->setAttribute('role_id', SkillConfig::USER_TRAINER);
                $userRole->setAttribute('user_id', $model->id);
                $userRole->save(false);
                $profile = new Profiles();
                $profile->termcondition = SkillConfig::STATUS_ACTIVE;
                $profile->user_id = $model->id;
                $profile->save();
                $identity = new UserIdentity($model->username, $_POST['Users']['password']);
                $identity->trainerauthenticate();
               // pr( $identity);
                Yii::app()->user->login($identity);
                $_SESSION['id'] = Yii::app()->user->id;
                $this->sendRegistrationmail($model);
                $this->redirect(Yii::app()->createAbsoluteUrl('/myskillhippo'));
            }
        }
        $this->render('_trainer-registration', array('model' => $model));
    }

}
